import axios from "axios"
import { useUserStore } from '@/stores/user'
import router from "@/router";

const service = axios.create({
  baseURL: 'http://localhost:9527/pet',
  timeout: 50000, // request timeout
});

// const adminUserStroe = userStore()


const isAdminUrl = (url) => {
  const regex = /^\/admin\/.*$/;  
    
  // 测试URL是否匹配正则表达式  
  return regex.test(url);  
}

// 请求拦截处
service.interceptors.request.use(
  
  (config) => {
    // 检查store中石油存在请求头数据
    const userStore = useUserStore()
    console.log(userStore.adminToken)
    let tokenData = userStore.adminToken || userStore.clientToken || ""
    // console.log(tokenData)
    if(tokenData){
      config.headers.satoken = isAdminUrl(config.url) ? userStore.adminToken : userStore.clientToken 
    }
    return config;
  },
  (error) => {
    // 请求异常处理
    console.log(error); // for debug
    return Promise.reject(error);
  }
);

// 响应拦截处理
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    // 登陆失效时，返回登陆页
    // let token = store.state.user.token
    // if (res.code === -1 && token) {
    //   Message.error(res.msg || "Error");
    //   store.commit("user/logout")
    //   router.push({path:'/login'})
    // } 
    // const router = useRouter();
    console.log(response.config.url)
    console.log(isAdminUrl(response.config.url))
    if (res.code === -1) {
      const userStore = useUserStore()
      if(isAdminUrl(response.config.url)){
        router.push({ path: "/login" })
        userStore.adminToken = null
      } else{
        router.push({ path: "/home" })
        userStore.clientToken = null
      }
    }
    if (res.code) {
      Message.error(res.msg || "Error");
    }
    // tryHideFullScreenLoading()
    return res;
    
  },
  (error) => {
    // Message.error(error || "Error");
    // tryHideFullScreenLoading()
    return Promise.reject(error);
  }
);

export default service;